// pages/index/houseInfo/houseInfo.js
import api from '../../../config/api'
import path from '../../../config/path'
const app = getApp()
const bubbleMixin = require('../../../utils/page-mixin');
const { $Message, $Toast } = require('../../../dist/base/index')

Page({
  ...bubbleMixin,
  data: {
    id: '',
    picLocal: app.globalData.picLocal,
    baseHeadPic: app.globalData.picLocal + '/default/head/head.png',
    imageSetting: {
      indicatorDots: true,
      autoplay: true,
      interval: 5000,
      duration: 500
    },
    houseResource: {},
    owner: {},
    markers: [{
      id: 1,
      iconPath: "../../../images/icon/location.png",
      height: 34,
      latitude: 23.099994,
      longitude: 113.324520,
    }],
    collection: false,
    showModal: false,
    showModal2: false,
    viewTime: '',
    viewDate: '',
    startDate: '',  // 新增：租房申请开始时间
    endDate: '',
    viewRemark: '', // 新增：预约备注
    applyRemark: '', // 新增：租房申请备注
    appointmentLoading: false,
    applyLoading: false,
    currentUser: null, // 当前登录用户
    isOwner: false,    // 是否是房主
    isNormalUser: false // 是否是普通用户
  },

  onLoad(options) {
    this.setData({ id: options.id || '' })
    this.initDates()
    this.loadCurrentUser()
    this.loadHouseDetail()
  },

  // 加载当前用户信息
  loadCurrentUser() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        currentUser: userInfo,
        isNormalUser: userInfo.role === 0
      })
    }
  },

  initDates() {
    const today = new Date()
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
    const defaultEnd = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000)
    this.setData({
      viewDate: this.formatDate(tomorrow),
      viewTime: '10:00',
      startDate: this.formatDate(tomorrow), // 默认开始时间为明天
      endDate: this.formatDate(defaultEnd),
      viewRemark: '',
      applyRemark: ''
    })
  },

  formatDate(date) {
    const y = date.getFullYear()
    const m = `${date.getMonth() + 1}`.padStart(2, '0')
    const d = `${date.getDate()}`.padStart(2, '0')
    return `${y}-${m}-${d}`
  },

  loadHouseDetail() {
    if (!this.data.id) { return }
    api.get('house', path.path.getHouseDetail + this.data.id).then(res => {
      const detail = res.data || {}
      const houseResource = this.normalizeHouse(detail)
      const owner = this.normalizeOwner(detail)
      const markers = this.data.markers.map(marker => ({
        ...marker,
        latitude: detail.latitude || marker.latitude,
        longitude: detail.longitude || marker.longitude
      }))
      
      // 检查是否是房主
      const isOwner = this.data.currentUser && this.data.currentUser.id === detail.landlordId
      
      this.setData({ 
        houseResource, 
        owner, 
        markers,
        isOwner 
      })
      this.refreshCollection(detail.id)
    }).catch(err => {
      console.log('loadHouseDetail error', err)
      $Toast({ content: '加载房源信息失败' })
    })
  },

  normalizeHouse(detail) {
    // 解析设施信息
    let facilities = []
    try {
      facilities = detail.facilities ? JSON.parse(detail.facilities) : []
    } catch (e) {
      facilities = []
    }

    return {
      ...detail,
      id: detail.id,
      price: detail.price || 0,
      description: detail.description || '',
      roomType: detail.roomType || '',
      province: detail.province || '',
      city: detail.city || '',
      district: detail.district || '',
      picList: (detail.picList || []).map(pic => ({
        url: pic.url || pic.path || pic
      })),
      facilities: facilities,
      latitude: detail.latitude,
      longitude: detail.longitude,
      landlordId: detail.landlordId // 确保有landlordId字段
    }
  },

  normalizeOwner(detail) {
    const gender = detail.landlordGender !== undefined
      ? detail.landlordGender
      : detail.ownerGender
    return {
      name: detail.landlordName || detail.ownerName || '房东',
      mobile: detail.landlordPhone || detail.ownerPhone || '',
      headUrl: detail.landlordAvatar || detail.ownerAvatar || '',
      sex: gender === undefined || gender === null ? '' : `${gender}`
    }
  },

  refreshCollection(houseId) {
    const token = wx.getStorageSync('token')
    if (!token) {
      this.setData({ collection: false })
      return
    }
    api.get('house', path.path.checkCollection + houseId).then(res => {
      const isCollected = res.data && (res.data.isCollected || res.data.collected)
      this.setData({ collection: !!isCollected })
    }).catch(() => {
      this.setData({ collection: false })
    })
  },

  ensureLogin() {
    const token = wx.getStorageSync('token')
    const userInfo = wx.getStorageSync('userInfo')
    if (!token || !userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/userInfo/myInfo'
        })
      }, 1000)
      return null
    }
    return userInfo
  },

  toApplyLook() {
    const user = this.ensureLogin()
    if (!user) return
    this.setData({ showModal: true })
  },

  toApplyRent() {
    const user = this.ensureLogin()
    if (!user) return
    this.setData({ showModal2: true })
  },

  // 编辑房源
  toEditHouse() {
    wx.navigateTo({
      url: `/pages/userInfo/myhouse/abouthouse/abouthouse?id=${this.data.houseResource.id}`
    })
  },

  modal_click_Hidden() {
    this.setData({ showModal: false })
  },

  modal_click_Hidden2() {
    this.setData({ showModal2: false })
  },

  bindDateChange(e) {
    this.setData({ viewDate: e.detail.value })
  },

  bindDateChange2(e) {
    this.setData({ endDate: e.detail.value })
  },

  // 新增：开始时间选择器事件处理
  bindDateChange3(e) {
    this.setData({ startDate: e.detail.value })
  },

  bindTimeChange(e) {
    this.setData({ viewTime: e.detail.value })
  },

  // 新增：预约备注输入事件处理
  bindViewRemarkChange(e) {
    this.setData({ viewRemark: e.detail.value })
  },

  // 新增：租房申请备注输入事件处理
  bindApplyRemarkChange(e) {
    this.setData({ applyRemark: e.detail.value })
  },

  // 预约看房 - 根据后端接口调整
  Sure() {
    const user = this.ensureLogin()
    if (!user) return
    if (!this.data.viewDate || !this.data.viewTime) {
      $Toast({ content: '请先选择日期和时间' })
      return
    }
    const contactPhone = user.phone || user.mobile || ''
    if (!contactPhone) {
      $Toast({ content: '请先完善个人联系方式' })
      return
    }
    
    // 构建预约时间
    const appointmentTime = new Date(`${this.data.viewDate} ${this.data.viewTime}`).toISOString()
    
    this.setData({ appointmentLoading: true })
    
    // 根据后端接口创建预约看房
    const appointmentData = {
      userId: user.id,
      houseId: this.data.houseResource.id,
      landlordId: this.data.houseResource.landlordId,
      appointmentTime: appointmentTime,
      contactPhone: contactPhone,
      remark: this.data.viewRemark || '' // 添加备注
    }
    
    api.post('apply', path.path.createAppointment, appointmentData).then(() => {
      $Message({
        content: '预约看房申请已提交',
        type: 'success'
      })
      this.setData({ 
        showModal: false,
        viewRemark: '' // 重置备注
      })
    }).catch((err) => {
      console.log('预约看房失败:', err)
      $Toast({ content: '提交失败，请稍后重试' })
    }).finally(() => {
      this.setData({ appointmentLoading: false })
    })
  },

  // 租房申请 - 根据后端接口调整
  Sure2() {
    const user = this.ensureLogin()
    if (!user) return
    if (!this.data.startDate || !this.data.endDate) {
      $Toast({ content: '请选择开始和结束日期' })
      return
    }
    const contactPhone = user.phone || user.mobile || ''
    if (!contactPhone) {
      $Toast({ content: '请先完善个人联系方式' })
      return
    }
    
    // 构建时间
    const rentStartTime = new Date(this.data.startDate + ' 00:00:00').toISOString()
    const rentEndTime = new Date(this.data.endDate + ' 23:59:59').toISOString()
    
    this.setData({ applyLoading: true })
    
    // 根据后端接口创建租房申请
    const applyData = {
      userId: user.id,
      houseId: this.data.houseResource.id,
      landlordId: this.data.houseResource.landlordId,
      rentStartTime: rentStartTime,
      rentEndTime: rentEndTime,
      contactPhone: contactPhone,
      remark: this.data.applyRemark || '' // 添加备注
    }
    
    api.post('apply', path.path.createApply, applyData).then(() => {
      $Message({
        content: '租房申请已提交',
        type: 'success'
      })
      this.setData({ 
        showModal2: false,
        applyRemark: '' // 重置备注
      })
    }).catch((err) => {
      console.log('租房申请失败:', err)
      $Toast({ content: '租房申请提交失败' })
    }).finally(() => {
      this.setData({ applyLoading: false })
    })
  },

  // 收藏功能
  collectionChange() {
    const user = this.ensureLogin()
    if (!user) return
    if (!this.data.houseResource.id) return
    const houseId = this.data.houseResource.id
    
    if (this.data.collection) {
      // 取消收藏
      api.remove('house', path.path.removeCollection + houseId).then(() => {
        $Toast({ content: '已取消收藏' })
        this.setData({ collection: false })
      }).catch(() => {
        $Toast({ content: '取消收藏失败' })
      })
    } else {
      // 添加收藏
      const url = `${path.path.addCollection}?houseId=${houseId}`
      api.post('house', url, {}).then(() => {
        $Toast({ content: '收藏成功' })
        this.setData({ collection: true })
      }).catch(() => {
        $Toast({ content: '收藏失败，请稍后再试' })
      })
    }
  },

  toPrivateChat() {
    const user = this.ensureLogin()
    if (!user) return
    
    wx.navigateTo({
      url: `/pages/userInfo/chatmessage/chatmessage?userId=${this.data.houseResource.landlordId}&userName=${this.data.owner.name}&avatar=${this.data.owner.headUrl}`
    })
  }
})